﻿using System;
using System.Management.Automation;
using System.Management.Automation.Host;

using Cognifide.PowerShell.Shell.Settings;

using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;

namespace Cognifide.PowerShell.Shell.Commands
{
    [Cmdlet("Set", "HostProperty", SupportsShouldProcess = true, DefaultParameterSetName = "Name")]
    public class SetHostPropertyCommand : BaseCommand
    {
        [Parameter]
        public ConsoleColor ForegroundColor { get; set; }

        [Parameter]
        public ConsoleColor BackgroundColor { get; set; }

        [Parameter]
        public int HostWidth { get; set; }

        [Parameter]
        public SwitchParameter Persist { get; set; }

        protected override void ProcessRecord()
        {

            PsConsoleSettings.Instance.Load();

            if (MyInvocation.BoundParameters.ContainsKey("ForegroundColor"))
            {
                Host.UI.RawUI.ForegroundColor = ForegroundColor;
                if (Persist.IsPresent)
                {
                    PsConsoleSettings.Instance.ForegroundColor = ForegroundColor;
                }
            }

            if(MyInvocation.BoundParameters.ContainsKey("BackgroundColor"))
            {
                Host.UI.RawUI.BackgroundColor = BackgroundColor;
                if (Persist.IsPresent)
                {
                    PsConsoleSettings.Instance.BackgroundColor = BackgroundColor;
                }
            }

            if(MyInvocation.BoundParameters.ContainsKey("HostWidth"))
            {
                Host.UI.RawUI.BufferSize = new Size(HostWidth, Int32.MaxValue);
                if (Persist.IsPresent)
                {
                    PsConsoleSettings.Instance.HostWidth = HostWidth;
                }
            }

            if (Persist.IsPresent)
            {
                PsConsoleSettings.Instance.Save();
            }
            

        }

        protected void Run(Sitecore.Web.UI.Sheer.ClientPipelineArgs args)
        {
            if (args.IsPostBack)
            {
                if ((!String.IsNullOrEmpty(args.Result)) && args.Result != "undefined" && args.Result != "null")
                {
                    Database db = Factory.GetDatabase(args.Parameters["database"]);
                    Item myItem = db.GetItem(new ID(args.Parameters["id"]));
                }
            }
            else
            {

                Sitecore.Context.ClientPage.ClientResponse.Input("My Message:"
                    , "My Default Value"
                    , Sitecore.Configuration.Settings.ItemNameValidation
                    , "'$Input' is not a valid name.", 255);
                args.WaitForPostBack();
            }
        }  
    }
}

